// pages/index/index.js
const math = require('../../utils/math.js')
Page({
  data: {
    target: 'num1',
    num1: '0',
    num2: '0',
    op: '',
    num: '0',
    sub: ''
  },

  //页面初始化
  onLoad(options) {
      this.reset()
  },

  // 数字按钮处理
  numBtn(e) {
    const val = e.currentTarget.dataset.val
    let current = this.getNum()
    
    if (current === '0' && val !== '0') {
      current = val
    } else if (current !== '0') {
      current += val
    }
    
    this.setNum(current)
    this.setData({ num: current })
  },

  // 小数点处理
  dotBtn() {
    let current = this.getNum()
    if (current.indexOf('.') === -1) {
      current += '.'
      this.setNum(current)
      this.setData({ num: current })
    }
  },

  // 运算符处理
  opBtn(e) {
    const op = e.currentTarget.dataset.val
    if (this.op && this.num2 !== '0') {
      this.execBtn()
    }
    this.op = op
    this.changeNum2()
    this.setData({ 
      sub: `${this.num1} ${op}`,
      num: '0'
    })
  },

  // 等号处理
  execBtn() {
    if (!this.op || this.num2 === '0') return
    
    const result = this.getResult()
    this.setData({
      sub: `${this.num1} ${this.op} ${this.num2} =`,
      num: result
    })
    this.reset()
    this.num1 = result
  },

  // 删除处理
  delBtn() {
    let current = this.getNum()
    if (current.length > 1) {
      current = current.slice(0, -1)
    } else {
      current = '0'
    }
    this.setNum(current)
    this.setData({ num: current })
  },

  // 正负号切换
  negBtn() {
    let current = this.getNum()
    if (current !== '0') {
      current = current.startsWith('-') ? 
        current.slice(1) : `-${current}`
      this.setNum(current)
      this.setData({ num: current })
    }
  },

  // 重置处理
  resetBtn() {
    this.reset()
    this.setData({ 
      num: '0',
      sub: ''
    })
  },

  // 进行计算
  setNum(num) { this[this.target] = num },
  getNum() { return this[this.target] },
  changeNum2() { this.target = 'num2' },
  reset() { this.num1 = this.num2 = '0'; this.target = 'num1'; this.op = '' },
  
  getResult() {
    if (this.op === '＋') return math.add(this.num1, this.num2) + ''
    if (this.op === '－') return math.sub(this.num1, this.num2) + ''
    if (this.op === '×') return math.mul(this.num1, this.num2) + ''
    if (this.op === '÷') return math.div(this.num1, this.num2) + ''
  }
})